#pragma once

#include "Protocol.hpp"
#include "epoller.hpp"

using namespace ns_epoll;

struct Task
{
  uint16_t _port;
  std::string _ip;
  request _rq;
  EventItem* _item;

  Task(uint16_t port, std::string& ip, request& rq, EventItem* item)
    :_port(port)
    ,_ip(ip)
    ,_rq(rq)
    ,_item(item)
  {}
  void Run()
  {
    std::cout << "[" << _ip << "]:[" << _port  << "]# "<< _rq._num1 << _rq._op << _rq._num2 << "=?"<< std::endl;
    response rp;
    switch(_rq._op)
    {
      case '+':
        rp._result = _rq._num1 + _rq._num2; 
        break;
      case '-':
        rp._result = _rq._num1 - _rq._num2; 
        break;
      case '*':
        rp._result = _rq._num1 * _rq._num2; 
        break;
      case '/':
        if (_rq._num2 == 0){
          rp._code = 1;
        }
        else{
          rp._result = _rq._num1 / _rq._num2; 
        }
        break;
      default:
        rp._code = 2;
        break;
    } 
    // 4.形成响应报头
    std::string rps;
    // code:result
    rps += std::to_string(rp._code);
    rps += ':';
    rps += std::to_string(rp._result);
    // 写回
    Epoller* epoller = _item->_R;
    int sock = _item->_sock;
    _item->_outbuffer += rps;
    // 添加分隔符
    _item->_outbuffer += '?';
    // 打开写开关
    if (!_item->_outbuffer.empty()) epoller->EnableReadWrite(sock, true, true);
  }
};
